<script lang="ts" setup>
import { ref } from 'vue'
import { mobileRules, codeRules } from '@/utils/rules'
import { getCodeService } from '@/api/user'
import { Toast, type FormInstance } from 'vant'
// import { bindMobileService } from '@/api/user'

const mobile = ref('')
const code = ref('')
// 绑定手机号
const bindMobile = async () => {}

// 表单实例
const formRef = ref<FormInstance>()
// 发送验证码
const countdown = ref(0) // 倒计时时间
let timer: any = null // 存储定时器id
const getCode = async () => {
  try {
    await formRef.value?.validate(['mobile'])
    Toast.success('发送验证码成功')
  } catch (error) {
    return Toast.fail('请输入正确的手机号')
  }
  try {
    const res = await getCodeService(mobile.value, 'bindMobile')
    code.value = res.code
    countdown.value = 60 // 设置倒计时时间
    // 开启定时器
    timer = setInterval(() => {
      countdown.value--
      if (countdown.value === 0) clearInterval(timer)
    }, 1000)
  } catch (error) {}
}
</script>

<template>
  <div class="bind-mobile">
    <cp-nav-bar title="qq登录-绑定手机号" />
    <div class="bind-title">
      <h3>手机号绑定</h3>
    </div>
    <!-- 绑定手机号表单 -->
    <van-form autocomplete="off" @submit="bindMobile" ref="formRef">
      <van-field
        placeholder="请输入手机号"
        type="tel"
        v-model="mobile"
        :rules="mobileRules"
        name="mobile"
      ></van-field>
      <van-field :placeholder="'请输入验证码'" type="text" v-model="code" :rules="codeRules">
        <template #button>
          <span class="get-code" @click="getCode" v-if="countdown === 0">获取验证码</span>
          <span class="sended-code" v-else>{{ countdown }}秒后重新获取</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit">立 即 绑 定</van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
.bind-mobile {
  box-sizing: border-box;
  height: 100vh;
  padding-top: 46px;
  .bind-title {
    padding: 30px 30px 40px;
    h3 {
      font-weight: 400;
      font-size: 24px;
    }
  }
  .van-form {
    padding: 0 14px;
    .get-code {
      color: var(--cp-primary);
    }
    .sended-code {
      color: var(--cp-price);
    }
    .cp-cell {
      height: 52px;
      padding: 14px 16px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
    }
  }
}
</style>
